package net.stogi.unicore.beyond.io.client.input.datefield;

import net.stogi.unicore.beyond.api.model.InputDefinition;
import net.stogi.unicore.beyond.io.client.input.core.InputField;

import com.extjs.gxt.ui.client.widget.form.DateField;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.Widget;

public class DateInputField implements InputField {

	protected final DateField field = new DateField();

	protected DateTimeFormat format;

	protected InputDefinition inputDefinition;

	public DateInputField(InputDefinition inputDefinition) {
		this(inputDefinition.getInputType().getName());
		this.inputDefinition = inputDefinition;
		initField();
	}

	@SuppressWarnings("unused")
	private DateInputField() {}

	private DateInputField(String inputTypeName) {
		if (!"datefield".equals(inputTypeName)) {
			throw new IllegalArgumentException("Input definition is not type of 'datefield'");
		}
	}

	@Override
	public Widget asWidget() {
		return field;
	}

	@Override
	public String getValue() {
		String value = null;
		
		if (field.getValue() != null) {
			value = DateTimeFormat.getFullDateFormat().format(field.getValue());
		}
		
		return value;
	}

	@Override
	public void setValue(String value) {
		field.setValue(format.parse(value));
	}

	private void initField() {
		field.setFieldLabel(inputDefinition.getName());
		field.setAllowBlank(Boolean.parseBoolean(inputDefinition.getProperty("empty").getValue()));
		// Last date.
		if (inputDefinition.getProperty("last").getValue() != null) {
			field.setMaxValue(DateTimeFormat.getFullDateFormat().parse(inputDefinition.getProperty("last").getValue()));
		}
		// First date.
		if (inputDefinition.getProperty("first").getValue() != null) {
			field.setMinValue(DateTimeFormat.getFullDateFormat().parse(inputDefinition.getProperty("first").getValue()));
		}
		// Date pattern.
		if (inputDefinition.getProperty("pattern").getValue() != null) {
			format = DateTimeFormat.getFormat(inputDefinition.getProperty("pattern").getValue());
		}
		// Default pattern 'yyyy-MM-dd'.
		else {
			format = DateTimeFormat.getFormat("yyyy-MM-dd");
		}
		field.getPropertyEditor().setFormat(format);
	}

	@Override
	public void setError(String error) {
		if (error != null) {
			field.forceInvalid(error);
		}
		else {
			field.clearInvalid();
		}
	}
}
